<template>
  <div class="employees-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">普通员工管理</h1>
        <p class="page-desc">管理企业普通员工信息</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          添加员工
        </el-button>
        <el-button type="success" @click="handleBatchImport">
          <el-icon>
            <Upload />
          </el-icon>
          批量导入
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入员工姓名" clearable style="width: 150px" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="部门">
          <el-select v-model="searchForm.department" placeholder="请选择部门" clearable style="width: 150px">
            <el-option label="技术部" value="技术部" />
            <el-option label="产品部" value="产品部" />
            <el-option label="运营部" value="运营部" />
            <el-option label="市场部" value="市场部" />
            <el-option label="财务部" value="财务部" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位">
          <el-input v-model="searchForm.position" placeholder="请输入职位" clearable style="width: 150px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="在职" value="active" />
            <el-option label="离职" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 员工列表 -->
    <el-card class="table-card">
      <el-table :data="tableData" v-loading="loading" stripe style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />

        <el-table-column prop="employeeId" label="工号" width="100" />

        <!-- 员工信息 -->
        <el-table-column label="员工信息" min-width="200">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="40" :src="row.avatar">
                <el-icon>
                  <User />
                </el-icon>
              </el-avatar>
              <div class="info-content">
                <div class="user-name">{{ row.name }}</div>
                <div class="user-email">{{ row.email }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 部门职位 -->
        <el-table-column label="部门/职位" min-width="150">
          <template #default="{ row }">
            <div class="dept-info">
              <div class="department">{{ row.department }}</div>
              <div class="position">{{ row.position }}</div>
            </div>
          </template>
        </el-table-column>

        <!-- 联系方式 -->
        <el-table-column label="联系方式" width="130">
          <template #default="{ row }">
            <div class="contact-info">
              <div class="phone">{{ row.phone || '-' }}</div>
            </div>
          </template>
        </el-table-column>

        <!-- 入职时间 -->
        <el-table-column label="入职时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.joinDate) }}
          </template>
        </el-table-column>

        <!-- 工作年限 -->
        <el-table-column label="工作年限" width="100">
          <template #default="{ row }">
            {{ calculateWorkYears(row.joinDate) }}
          </template>
        </el-table-column>

        <!-- 状态 -->
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              <el-icon>
                <View />
              </el-icon>
              查看
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>
            <el-button v-if="row.status === 'active'" type="warning" link @click="handleResign(row)">
              <el-icon>
                <OfficeBuilding />
              </el-icon>
              离职
            </el-button>
            <el-button v-else type="success" link @click="handleRehire(row)">
              <el-icon>
                <UserFilled />
              </el-icon>
              复职
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedRows.length > 0">
        <span class="selected-info">已选择 {{ selectedRows.length }} 项</span>
        <el-button type="warning" @click="handleBatchResign">
          <el-icon>
            <OfficeBuilding />
          </el-icon>
          批量离职
        </el-button>
        <el-button type="danger" @click="handleBatchDelete">
          <el-icon>
            <Delete />
          </el-icon>
          批量删除
        </el-button>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 添加/编辑员工对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px" @close="handleDialogClose">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" placeholder="请输入员工姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工号" prop="employeeId">
              <el-input v-model="formData.employeeId" placeholder="请输入工号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-select v-model="formData.department" placeholder="请选择部门" style="width: 100%">
                <el-option label="技术部" value="技术部" />
                <el-option label="产品部" value="产品部" />
                <el-option label="运营部" value="运营部" />
                <el-option label="市场部" value="市场部" />
                <el-option label="财务部" value="财务部" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="formData.position" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入职时间" prop="joinDate">
              <el-date-picker v-model="formData.joinDate" type="date" placeholder="请选择入职时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="直属上级" prop="supervisor">
              <el-input v-model="formData.supervisor" placeholder="请输入直属上级" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="头像" prop="avatar">
          <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload"
            :http-request="handleAvatarUpload">
            <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Upload,
  Search,
  Refresh,
  User,
  View,
  Edit,
  OfficeBuilding,
  UserFilled,
  Delete
} from '@element-plus/icons-vue'
import usePageState from './hooks/usePageState'
import type { EmployeeBase } from '@/types'

const
  {
    loading,
    submitLoading,
    dialogVisible,
    isEdit,
    formRef,
    selectedRows,
    searchForm,
    pagination,
    tableData,
    formData,
    formRules,
    dialogTitle
  } = usePageState()

// 方法定义

/**
 * 格式化日期
 */
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

/**
 * 计算工作年限
 */
const calculateWorkYears = (joinDate: string) => {
  const join = new Date(joinDate)
  const now = new Date()
  const years = now.getFullYear() - join.getFullYear()
  const months = now.getMonth() - join.getMonth()

  if (years === 0) {
    return `${months}个月`
  } else if (months >= 0) {
    return `${years}年${months}个月`
  } else {
    return `${years - 1}年${12 + months}个月`
  }
}

/**
 * 搜索
 */
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

/**
 * 重置搜索
 */
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    email: '',
    department: '',
    position: '',
    status: ''
  })
  handleSearch()
}

/**
 * 添加员工
 */
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

/**
 * 批量导入
 */
const handleBatchImport = () => {
  ElMessage.info('批量导入功能开发中')
  // TODO: 实现批量导入功能
}

/**
 * 查看员工详情
 */

const handleView = (row: EmployeeBase) => {
  ElMessage.info(`查看员工：${row.name}`)
  // TODO: 实现查看详情功能
}

/**
 * 编辑员工
 */

const handleEdit = (row: EmployeeBase) => {
  isEdit.value = true
  Object.assign(formData, {
    id: row.id,
    employeeId: row.employeeId,
    name: row.name,
    email: row.email,
    phone: row.phone,
    department: row.department,
    position: row.position,
    joinDate: row.joinDate,
    supervisor: row.supervisor,
    avatar: row.avatar,
    remark: row.remark
  })
  dialogVisible.value = true
}

/**
 * 员工离职
 */

const handleResign = (row: EmployeeBase) => {
  ElMessageBox.confirm(
    `确定要将员工「${row.name}」设置为离职状态吗？`,
    '员工离职确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    row.status = 'inactive'
    ElMessage.success('员工离职处理成功')
    // TODO: 调用API更新状态
  })
}

/**
 * 员工复职
 */

const handleRehire = (row: EmployeeBase) => {
  ElMessageBox.confirm(
    `确定要将员工「${row.name}」重新设置为在职状态吗？`,
    '员工复职确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(() => {
    row.status = 'active'
    ElMessage.success('员工复职处理成功')
    // TODO: 调用API更新状态
  })
}

/**
 * 选择改变
 */

const handleSelectionChange = (selection: Partial<EmployeeBase>[]) => {
  selectedRows.value = selection
}

/**
 * 批量离职
 */
const handleBatchResign = () => {
  ElMessageBox.confirm(
    `确定要将选中的 ${selectedRows.value.length} 名员工设置为离职状态吗？`,
    '批量离职确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {

    selectedRows.value.forEach((row: Partial<EmployeeBase>) => {
      row.status = 'inactive'
    })
    ElMessage.success('批量离职处理成功')
    selectedRows.value = []
    // TODO: 调用API批量更新状态
  })
}

/**
 * 批量删除
 */
const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 名员工吗？此操作不可恢复！`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(() => {
    ElMessage.success('批量删除成功')
    selectedRows.value = []
    loadData()
    // TODO: 调用API批量删除
  })
}

/**
 * 分页大小改变
 */
const handleSizeChange = (size: number) => {
  pagination.size = size
  loadData()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadData()
}

/**
 * 对话框关闭
 */
const handleDialogClose = () => {
  resetForm()
}

/**
 * 重置表单
 */
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    employeeId: '',
    name: '',
    email: '',
    phone: '',
    department: '',
    position: '',
    joinDate: '',
    supervisor: '',
    avatar: '',
    remark: ''
  })
  formRef.value?.clearValidate()
}

/**
 * 头像上传前验证
 */
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

/**
 * 处理头像上传
 */

const handleAvatarUpload = (options: { file: Blob }) => {
  // TODO: 实现头像上传逻辑
  const reader = new FileReader()
  reader.onload = (e) => {
    formData.avatar = e.target?.result as string
  }
  reader.readAsDataURL(options.file)
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true

    // TODO: 调用API保存数据
    setTimeout(() => {
      submitLoading.value = false
      dialogVisible.value = false
      ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
      loadData()
    }, 1000)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

/**
 * 加载数据
 */
const loadData = () => {
  loading.value = true
  // TODO: 调用API获取数据
  setTimeout(() => {
    pagination.total = 3
    loading.value = false
  }, 500)
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.employees-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 4px 0;
}

.page-desc {
  color: #909399;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.info-content {
  flex: 1;
}

.user-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
}

.user-email {
  font-size: 12px;
  color: #909399;
}

.dept-info {
  line-height: 1.5;
}

.department {
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
}

.position {
  font-size: 12px;
  color: #909399;
}

.contact-info {
  line-height: 1.5;
}

.phone {
  color: #303133;
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 0;
  border-top: 1px solid #e4e7ed;
  margin-top: 12px;
}

.selected-info {
  color: #409eff;
  font-weight: 500;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }

  .header-right {
    align-self: stretch;
    justify-content: space-between;
  }
}
</style>
